package com.carlos.gateway.config;

import com.carlos.gateway.security.handler.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;


/**
 * @author 李健成
 * @date 2021/10/27
 */

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    @Autowired
    private JsonAuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private JsonAuthenticationFailureHandler authenticationFailureHandler;

    @Autowired
    private JsonLogoutSuccessHandler logoutSuccessHandler;

    @Autowired
    private JsonLogoutHandler logoutHandler;

    @Autowired
    private AuthEntryPoint authEntryPoint;

    /**
     * 白名单
     */
    private static final String[] AUTH_WHITELIST = {
            "/login",
            "/logout"
    };

    @Bean
    SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        return http.formLogin()
                .authenticationSuccessHandler(authenticationSuccessHandler)
                .authenticationFailureHandler(authenticationFailureHandler)
                .authenticationEntryPoint(authEntryPoint)
                .and()
                .logout()
                .logoutHandler(logoutHandler)
                .logoutSuccessHandler(logoutSuccessHandler)
                .and()
                .csrf().disable()
                .httpBasic().disable()
                .authorizeExchange()
                .pathMatchers(AUTH_WHITELIST).permitAll()
//                .anyExchange().access()
                .and().build();
    }

}
